﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace ParkingLot.Utility.StockHelp
{
    public class UDPReceiveHelp
    {
        #region 字段
        private readonly UdpClient m_NewSock;

        private Thread m_Thread;

        public bool IsStart { private set; get; } = false;
        /// <summary>
        /// 加入的广播组的列表
        /// </summary>
        private List<IPAddress> m_JoinMulticastList = new List<IPAddress>();

        private  IPEndPoint m_receivIpEndPoint;

        private int m_Port;

        /// <summary>
        /// 收到数据包后事件
        /// </summary>
        public event Action<byte[]> ReceivedPacket;

        public UDPReceiveHelp(UdpClient udpClient,IPEndPoint receivIpEndPoint)
        {
            m_NewSock = udpClient;
            m_receivIpEndPoint = receivIpEndPoint;
        }
        /// <summary>
        /// 开始监听
        /// </summary>
        public void Start()
        {
            this.IsStart = true;
            m_Thread = new Thread(ThreadStart);
            m_Thread.IsBackground= true;
            m_Thread.Start();
        }

        /// <summary>
        /// 停止监听
        /// </summary>
        public void Stop()
        {
            if (m_NewSock != null)
            {
                m_NewSock.Close();
            }

            try
            {
                m_Thread.Abort();
            }
            catch (Exception ex)
            {
            }

        }


        private void ThreadStart()
        {
            try
            {
                byte[] data;

                ;
                m_NewSock.Client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);
                m_NewSock.Client.Bind(m_receivIpEndPoint);

                //m_NewSock.EnableBroadcast = true;
                //m_NewSock.MulticastLoopback = true;
               
                while (true)
                {
                    try
                    {
                        data = m_NewSock.Receive(ref m_receivIpEndPoint);
                        if (ReceivedPacket != null)
                        {
                            ReceivedPacket(data);
                        }
                    }
                    catch (Exception exception)
                    {
                        //MessageBox.Show(exception.Message);
                    }
                }
            }
            catch (Exception e)
            {
                //MessageBox.Show(e.Message);
            }
        }
        #endregion

    }
}
